package com.xzakota.minesweeper.ui.frame;

import com.xzakota.minesweeper.Client;
import com.xzakota.minesweeper.R;
import com.xzakota.minesweeper.SingleTaskExecutor;
import com.xzakota.minesweeper.contant.ConstantPool;
import com.xzakota.minesweeper.controller.GameResource;
import com.xzakota.minesweeper.log.XLogger;
import com.xzakota.minesweeper.msg.*;
import com.xzakota.minesweeper.ui.dialog.IPDialog;
import com.xzakota.minesweeper.ui.dialog.RoomDialog;
import com.xzakota.minesweeper.ui.dialog.SignInDialog;
import com.xzakota.minesweeper.ui.dialog.SignOutDialog;
import com.xzakota.minesweeper.ui.dialog.templae.MessageDialog;
import com.xzakota.minesweeper.ui.dialog.templae.OptionDialog;
import com.xzakota.minesweeper.ui.dialog.templae.SwingWorkerWaitDialog;
import com.xzakota.minesweeper.util.JSONFileUtils;
import com.xzakota.minesweeper.widget.button.SplashButton;
import com.xzakota.minesweeper.widget.image.RoundImage;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.net.URL;
import java.util.concurrent.CountDownLatch;

/**
 * 启动界面
 *
 * @author Xzakota
 */
public class SplashFrame extends AbstractBaseFrame {
    public SplashFrame() {
        super(ConstantPool.APP_NAME_CN);

        setIconImage(GameResource.getImageResource(R.Image.APP_ICON));
        setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
        initLayout();
        setLocationRelativeTo(null);

        addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                exitApp();
            }

            @Override
            public void windowClosed(WindowEvent e) {
                XLogger.info("客户端关闭启动界面");

                Client.getClient().close();
                JSONFileUtils.commit();
                System.exit(1);
            }
        });
    }

    public void initLayout() {
        setSize(790, 450);

        JPanel rootPanel = new JPanel(new BorderLayout()) {
            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                Image image = GameResource.getImageResource(R.Image.SPLASH_BG);
                g.drawImage(image, 0, 0, getWidth(), getHeight(), null);
            }
        };

        // =================== 用户面板 ===================
        JPanel leftPanel = new JPanel();
        leftPanel.setOpaque(false);
        leftPanel.setLayout(new FlowLayout(FlowLayout.LEFT, 10, 0));
        leftPanel.setBorder(new EmptyBorder(10, 20, 0, 0));

        RoundImage userAvatar = new RoundImage(GameResource.getImageResource(R.Image.USER_AVATAR), 40, 40);
        leftPanel.add(userAvatar);

        JButton loginButton = new JButton("去登录");
        loginButton.setFocusable(false);
        loginButton.addActionListener(event -> {
            if (!JSONFileUtils.has(ConstantPool.SETTINGS_SERVER_IP)) {
                Object ipResult = new IPDialog().showWindow2();
                if (!(ipResult instanceof Boolean && (Boolean) ipResult)) {
                    return;
                } else {
                    new Thread(() -> {
                        Client.initSocket(JSONFileUtils.getString(ConstantPool.SETTINGS_SERVER_IP));
                        SingleTaskExecutor.submitTask(Client.getClient());
                    }).start();
                }
            }

            if (Client.getClient().currentUser != null) {
                Object signOutResult = new SignOutDialog(this).showWindow2();
                if (signOutResult instanceof Boolean && (Boolean) signOutResult) {
                    loginButton.setText("去登录");
                    userAvatar.setAvatarImage(GameResource.getImageResource(R.Image.USER_AVATAR));
                }
            } else {
                Object signInResult = new SignInDialog(this).showWindow2();
                if (signInResult instanceof Boolean && (Boolean) signInResult) {
                    loginButton.setText(JSONFileUtils.getString(ConstantPool.SETTINGS_USER_NAME));
                    try {
                        userAvatar.setAvatarImage(new URL("https://q1.qlogo.cn/g?b=qq&nk=" + Client.getClient().currentUser.qq + "&s=640"));
                    } catch (Exception e) {
                        XLogger.error("获取用户头像失败: " + e);
                    }
                }
            }
        });
        leftPanel.add(loginButton);

        rootPanel.add(leftPanel, BorderLayout.WEST);
        // ===============================================

        // =================== 右侧面板 ===================
        JPanel rightPanel = new JPanel();
        rightPanel.setOpaque(false);
        rightPanel.setLayout(new BoxLayout(rightPanel, BoxLayout.Y_AXIS));
        rightPanel.setBorder(new EmptyBorder(0, 0, 0, 100));

        ImageIcon logoIcon = new ImageIcon(GameResource.getImageResource(R.Image.APP_LOGO));
        logoIcon.setImage(logoIcon.getImage().getScaledInstance(65, 65, Image.SCALE_SMOOTH));
        JLabel logoLabel = new JLabel(ConstantPool.APP_NAME_CN, logoIcon, JLabel.CENTER);
        logoLabel.setFont(new Font("华文琥珀", Font.BOLD, 28));
        logoLabel.setIconTextGap(15);
        logoLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
        rightPanel.add(Box.createVerticalGlue());
        rightPanel.add(logoLabel);

        JButton singleGameButton = new SplashButton("单人游戏");
        singleGameButton.setAlignmentX(Component.CENTER_ALIGNMENT);
        singleGameButton.addActionListener(e -> {
            SinglePlayerGameFrame frame = new SinglePlayerGameFrame(this);
            hideWindow();
            frame.showWindow();
        });
        rightPanel.add(Box.createVerticalStrut(40));
        rightPanel.add(singleGameButton);

        JButton multiGameButton = new SplashButton("多人游戏");
        multiGameButton.setAlignmentX(Component.CENTER_ALIGNMENT);
        multiGameButton.addActionListener(e -> {
            if (Client.getClient().currentUser == null) {
                new MessageDialog("请先登录！").showWindow();
                return;
            }
            SwingWorkerWaitDialog waitDialog = new SwingWorkerWaitDialog();
            waitDialog.setTipText("正在查询房间中...");
            waitDialog.worker = new SwingWorkerWaitDialog.Worker() {
                @Override
                public Boolean doInBackground() {
                    GameAllRoomMsg sendMsg = new GameAllRoomMsg();

                    final boolean[] result = {false, false, false};

                    CountDownLatch latch = new CountDownLatch(1);
                    waitDialog.doReleaseEvent();
                    waitDialog.tempThread = new Thread(() -> {
                        MsgHandler handler = new MsgHandler() {
                            @Override
                            public void handle(BaseMsg msg) {
                                if (msg.code == MsgCode.BASE_SUCCESS) {
                                    result[0] = true;
                                }
                                MsgHandlerFactory.removeMsgHandler(MsgHandlerFactory.MSG_TYPE_GAME_ALL_ROOM, this);
                                latch.countDown();
                            }
                        };
                        MsgHandlerFactory.addMsgHandler(MsgHandlerFactory.MSG_TYPE_GAME_ALL_ROOM, handler);
                        Client.getClient().sendMsg(sendMsg);
                    });
                    waitDialog.tempThread.start();

                    try {
                        latch.await();
                    } catch (InterruptedException ex) {
                        throw new RuntimeException(ex);
                    }

                    return result[0];
                }

                @Override
                public void doneSuccess() {
                    RoomDialog frame = new RoomDialog(SplashFrame.this);
                    frame.showWindow();
                }

                @Override
                public void doneFail() {
                }
            };
            waitDialog.showWindow();
        });
        rightPanel.add(Box.createVerticalStrut(20));
        rightPanel.add(multiGameButton);

        JButton settingButton = new SplashButton("游戏选项");
        settingButton.setAlignmentX(Component.CENTER_ALIGNMENT);
        settingButton.addActionListener(e -> new IPDialog().showWindow());
        rightPanel.add(Box.createVerticalStrut(20));
        rightPanel.add(settingButton);

        JButton exitButton = new SplashButton("退出游戏");
        exitButton.setAlignmentX(Component.CENTER_ALIGNMENT);
        exitButton.addActionListener(e1 -> exitApp());
        rightPanel.add(Box.createVerticalStrut(20));
        rightPanel.add(exitButton);
        rightPanel.add(Box.createVerticalGlue());

        rootPanel.add(rightPanel, BorderLayout.EAST);
        // ===============================================

        // =================== 底部面板 ===================
        JPanel bottomPanel = new JPanel(new FlowLayout());
        bottomPanel.setOpaque(false);

        JLabel adLabel = new JLabel("抵制不良游戏，拒绝盗版游戏，注意自我保护，谨防上当受骗，适度游戏益脑，沉迷游戏伤身，合理安排时间，享受健康生活。");
        adLabel.setForeground(Color.WHITE);
        bottomPanel.add(adLabel);

        rootPanel.add(bottomPanel, BorderLayout.SOUTH);
        // ===============================================

        setContentPane(rootPanel);
    }

    private void exitApp() {
        OptionDialog dialog = new OptionDialog("退出游戏");
        dialog.setTitle("是否退出？");
        dialog.setConfirmAction(e2 -> {
            dialog.closeWindow();
            closeWindow();
        });
        dialog.showWindow2();
    }
}
